<?php
declare (strict_types = 1);

namespace app\index\model;
use think\facade\Db;

/**
 * @mixin think\Model
 */
class Topic extends \app\common\model\content\Topic
{
    const HOT_LIMIT = 7; //热门话题每页个数
    const HOT_TOTAL_PAGE = 3;//每页显示7个 共显示3页


    const LIMIT_NUM = 20; //话题列表limit

    const TOPIC_NUMBER = 6;//侧边栏显示话题个数



    /**
     * #获取一个月份的热门话题
     * @param $where array #检索条件
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getHotTopics(array $where = []){
        $cacheKey = json_encode(array_merge(['hot_topics'], $where));
        if (!$topic_info = cache($cacheKey)){

            $topic_ids = Db::name('article')
                ->where([
                    ['status', '=', Article::STATUS_PUB],
                    ['topic_id','>', 0],
                    ['create_time','>',strtotime('-1 month')]
                ])
                ->where($where)
                ->field('sum(visited) AS visited,topic_id')
                ->group('topic_id')
                ->order(['visited'=>'desc'])
                ->limit(static::HOT_LIMIT * static::HOT_TOTAL_PAGE)
                ->select()
                ->column('topic_id');

            $topic_info = static::where([
                'id'=> $topic_ids
            ])
                ->field(['id','name'])
                ->order(['update_time'=>'DESC'])
                ->select()
                ->each(function($item, $k){
                    $item->url = (string)url('topic/read',['id'=>$item->id]);
                })
                ->toArray();
            cache($cacheKey, $topic_info, 12 * 3600);
        }
        return $topic_info;
    }


    /**
     * 获取查询构造器
     * @param array $where
     * @return Topic
     */
    private static function getQuery(array $where){
        return static::where($where);
    }

    /**
     * 获取数目
     * @param array $where
     * @return int
     */
    public static function getCount(array $where=[]){
        return static::getQuery($where)->count();
    }

    /**
     * 获取topic数据列表
     * @param null $page
     * @param null $limit
     * @param array $where
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getList($page=null, $limit=null, array $where=[]){
        return static::getQuery($where)
            ->field(['id','name','desc','image','count','status','user_id','category_id','create_time'])
            ->with([/*'user','category'*/])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => empty($limit) || $limit < 1 || $limit > 15 ? static::LIMIT_NUM : $limit,
                'page'      => empty($page) || $page <= 0 ? 1 : $page,
            ])->each(function($item, $key){
                $item->imageUrl = $item->imageUrl;

                $item->topicUrl = (string) url('topic/read',['id'=>$item->id]);
                $item->authorUrl = (string) url('user/read',['id'=>$item->user_id]);
                //$item->categoryUrl = (string) url('category/read',['id'=>$item->category_id]);
            })->toArray();
    }

    /**
     * 根据用户获取最新话题
     */
    public static function getTopicsByUser(int $user_id){
        $cacheKey = 'author_topics_' . $user_id;

        if (!$at = cache($cacheKey)){
            $at = static::where(['user_id' => $user_id])
                ->field(['id','name','desc','user_id','image'])
                ->order(['update_time'=>'DESC','id'=>'DESC'])
                ->limit(static::TOPIC_NUMBER)
                ->select()
                ->each(function($item, $key){
                    $item->imageUrl = (string)$item->imageUrl;
                })
                ->toArray();
            cache($cacheKey, $at, 9 * 3600);
        }
        return $at;

    }



}
